package demo4;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: asus
 * Date: 2024-12-16
 * Time: 10:29
 */
public class KTop {
    Comparator<Integer> comparator = new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2-o1;
        }
    };
    public ArrayList<Integer> GetLeastNumbers_Solution (int[] input, int k) {
        if (input.length < k || k == 0) {
            return new ArrayList<>();
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(k, comparator);
        for (int i = 0; i < k; i++) {
            queue.offer(input[i]);
        }
        for (int i = k; i < input.length; i++) {
            if (input[i] < queue.peek()) {
                queue.poll();
                queue.offer(input[i]);
            }
        }
        return new ArrayList<>(queue);
    }
    //第k大
    public int findKth (int[] a, int n, int K) {
        // write code here
        PriorityQueue<Integer> queue = new PriorityQueue<>(K, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        for (int i = 0; i < K; i++) {
            queue.add(a[i]);
        }
        for (int i = K; i < n; i++) {
            if (a[i] > queue.peek()) {
                queue.poll();
                queue.offer(a[i]);
            }
        }
        return queue.peek();
    }
    public static void main(String[] args) {

    }
}
